// pages/visitorsAll/visitorsAll.js
var app = getApp();
import api from "../../common/api.js";
import { debounce } from "../../utils/utilsNew.js";
const computedBehavior = require('miniprogram-computed')
import * as transferData from "../../models/transferData.js";

Component({
  behaviors: [computedBehavior],

  /**
   * 组件的属性列表
   */
  properties: {
    tabConentIndex: {
      type: Number,
      value: 0
    }
  },

  /**
   * 页面的初始数据
   */
  data: {
    windowWidth: 0,
    windowHeight: 0,
    isFetching: true,
    isInited: false,
    // isGoOfficialAccount: false, //推送状态
    heightVi: 0,
    scene: app.globalData.scene,
    isContent: true,
    copyShowDialog: false,
    isContentImg: true,
    houseTypes: 'SALES',
    // nickNames:'',
    offoci: true,
    menuVisitor: [], //客户轨迹列表
    analyzeVisitor: [], //客户管理列表
    tabList: ["获客工具", "客户轨迹", "客户管理"],
    tabIndex: {customerToolsIndex: 0 ,recentlyVisitorIndex: 1,analyzeVisitorIndex: 2},
    defaultTabIndex: 0,
    searchTextValue: "",
    sortTitleList: [
      "最近访问",
      "最早访问",
      "房源从多到少",
      "房源从少到多",
      "浏览次数从多到少",
      "浏览次数从少到多"
    ],
    sortSelectedIndex: 0, //排序规则
    sortNickname: "", //排序昵称
    isShowSortPop: false,
    recentlyVisitorPage: 0, //最近访客当前page
    recentlyVisitorPageMax: 0, //最近访客数据的最大页数

    analyzeVisitorPage: 0, //访客分析当前page
    analyzeVisitorPageMax: 0, //访客分析的最大页数
    maxPageSize: 20, //单页最大数据长度

    isShowVisitorTools: false,
  },

  computed: {
    noVisitor(data) {
      return (data.defaultTabIndex == data.tabIndex.recentlyVisitorIndex && !data.menuVisitor.length) || (data.defaultTabIndex == data.tabIndex.analyzeVisitorIndex && !data.analyzeVisitor.length)
    },
    scrollHeight(data) {
      return data.windowHeight - 160
    },
  },

  observers: {
    tabConentIndex() {
      if (this.data.tabConentIndex != 1) {
        return
      }
      if (this.data.defaultTabIndex == this.data.tabIndex.customerToolsIndex) {
        if(!this.data.isShowVisitorTools) {
          this.setData({
            isShowVisitorTools: true
          })
        }
      }
      if (this.data.defaultTabIndex == this.data.tabIndex.analyzeVisitorIndex) {
        this.resetAnalyze()
        this.getVisiTorsAnalyzeList(1)
      }
      if (this.data.defaultTabIndex == this.data.tabIndex.recentlyVisitorIndex) {
        this.resetRecently()
        this.queryVisitorList()
      }
    }
  },

  lifetimes: {
    attached: function() {
      // 在组件实例进入页面节点树时执行
      // console.log("visitorsAll attached.............");
      this.handleInputChange = debounce(this.handleInputChange.bind(this))
      this.initSystemInfo()
      app.globalData.loginPromise.then(() => {
        this.setData({
          heightVi: app.globalData.windowHeight
        })
        this.initTab()
      })
    },
    detached: function() {
      // 在组件实例被从页面节点树移除时执行
    },
  },
  methods: {
    initTab() {
      let tab = transferData.getData('visitorsDefaultTab')
      if(tab) {
        tab = Number(tab)
        this.tabnavIndexChange({detail: {index: tab}})
        transferData.resetData('visitorsDefaultTab')
      }
    },

    initSystemInfo() {
      let t = this
      wx.getSystemInfo({
        success: function (res) {
          t.setData({
            windowWidth: res.windowWidth,
            windowHeight: res.windowHeight
          })
        }
      })
    },

    handleMaskMove() {},

    resetRecently() {
      // 需要重置，得到最新的访客记录
      this.data.recentlyVisitorPage = 0
      this.data.recentlyVisitorPageMax = 0
      this.data.menuVisitor.length = 0
    },

    resetAnalyze() {
      this.setData({
        isShowSortPop: false,
        sortSelectedIndex: 0,
        searchTextValue: ""
      })
      this.data.sortNickname = ""
      this.data.analyzeVisitorPage = 0
      this.data.analyzeVisitorPageMax = 0
      this.data.analyzeVisitor.length = 0
    },

    handleInputChange(e) {
      this.setData({
        searchTextValue: e.detail.value
      })
      this.data.sortNickname = e.detail.value
      this.data.analyzeVisitorPage = 0
      this.data.analyzeVisitorPageMax = 0
      this.getVisiTorsAnalyzeList(1)
    },

    handleMaskClick() {
      this.setData({
        isShowSortPop: false
      })
    },

    handleSortClick(e) {
      this.setData({
        sortSelectedIndex: e.currentTarget.dataset.index,
        isShowSortPop: false
      })
      this.data.analyzeVisitorPage = 0
      this.data.analyzeVisitorPageMax = 0
      this.getVisiTorsAnalyzeList(1)
    },

    handleToggleShowSortPop() {
      this.setData({
        isShowSortPop: !this.data.isShowSortPop
      })
    },

    // tab切换触发
    tabnavIndexChange(e) {
      let t = this
      let index = e.detail.index
      this.setData({
        defaultTabIndex: index
      })
      switch (index) {
        case t.data.tabIndex.customerToolsIndex:
          if(!t.data.isShowVisitorTools) {
            this.setData({
              isShowVisitorTools: true
            })
          }
        break
        case t.data.tabIndex.recentlyVisitorIndex:
          this.resetRecently()
          this.queryVisitorList()
          break;
        case t.data.tabIndex.analyzeVisitorIndex:
          this.resetAnalyze()
          this.getVisiTorsAnalyzeList(1)
          break;
      }
    },

    // 获取客户管理列表
    getVisiTorsAnalyzeList(page) {
      if (page > 1 && page > this.data.analyzeVisitorPageMax) {
        return
      }
      this.setData({isFetching: true})
      api.getVisiTorsAnalyzeList({
        nickname: this.data.sortNickname,
        sortType: this.data.sortSelectedIndex, // 0：最近访问，1：最早访问，2：房源从多到少，3：房源从少到多，4：浏览次数从多到少，5：浏览次数从少到多
        page,
        pageSize: this.data.maxPageSize
      }, (res) => {
        let content = res.data.content
        this.data.analyzeVisitorPage = content.page
        this.data.analyzeVisitorPageMax = content.total
        this.setData({
          analyzeVisitor: content.page == 1 ? content.rows : this.data.analyzeVisitor.concat(content.rows),
          isFetching: false,
        })
      })
    },

    // 滚动条到底部
    visitorScroolEvent(e) {
      if (this.data.defaultTabIndex == this.data.tabIndex.recentlyVisitorIndex) {
        this.queryVisitorList()
      }
      if (this.data.defaultTabIndex == this.data.tabIndex.analyzeVisitorIndex) {
        this.getVisiTorsAnalyzeList(this.data.analyzeVisitorPage + 1)
      }
    },

    // 获取客户轨迹列表
    queryVisitorList: function() {
      var that = this;
      if (this.data.defaultTabIndex !=  this.data.tabIndex.recentlyVisitorIndex) return;
      var data = new Object();
      data.page = this.data.recentlyVisitorPage + 1;
      data.pageSize = this.data.maxPageSize;
      if (data.page > 1 && data.page > this.data.recentlyVisitorPageMax) {
        return
      }
      this.setData({isFetching: true})
      api.visiTorsList(data, (res) => {
        let content = res.data.content
        var menuVisitor = content.rows;
        this.data.recentlyVisitorPage = content.page
        this.data.recentlyVisitorPageMax = content.total
        if (this.data.recentlyVisitorPageMax == 0) {
          this.data.recentlyVisitorPage = 0
        }
        if (menuVisitor.length == 0) {
          this.setData({
            isFetching: false
          })
        } else {
          that.setData({
            menuVisitor: this.data.menuVisitor.concat(menuVisitor),
            isFetching: false,
          })
        }
      })
    },

    //跳转房源列表
    goRentalHouseDetail(e) {
      const houdelid = e.currentTarget.dataset.houdelid;
      const houseTypes = e.currentTarget.dataset.housetype;
      wx.navigateTo({
        url: '/pages/house/RentalHouseDetail/RentalHouseDetail?houdelid=' + houdelid + "&from=1" + "&type=" + houseTypes,
      })
    },

    copyNickname: function(e) {
      var that = this;
      let nickNames = e.detail.nickname;
      that.setData({
        copyShowDialog: true
      })
      wx.hideToast();
      wx.setClipboardData({
        data: nickNames,
        success(res) {
          wx.hideToast();
        }
      })
    },

    toggleCopyShowDialog() {
      var that = this;
      that.setData({
        copyShowDialog: false
      })
    },

    hideNoHouDialog: function() {
      var that = this;
      wx.setStorageSync("isCon", '0')
      that.setData({
        isContent: false,
        isContentImg: true
      })
    },

    // 跳转获客工具列表
    onJumpVisitorToolsList(e) {
      let target = e.currentTarget.dataset.target || ''
      app.mobileLogin()
        .then(() => {
          wx.navigateTo({
            url: `/pages/visitors/tools/list/visitorToolsList?target=${target}`,
          })
        })
        .catch(() => {
          app.globalData.afterMobileAuthorCallBack = () => {
            wx.redirectTo({
              url: `/pages/visitors/tools/list/visitorToolsList?target=${target}`,
            })
          };
        })
    },

    // 置顶/取消置顶
    onSetTop(e) {
      let t = this
      let {target, status} = e.detail || {}
      if(!target || status == undefined) {
        wx.showToast({
          title: '操作失败,请稍后再试',
        })
        return
      }
      api.setVisiTorsAnalyzeTop({
        userId: target,
        toppingStatue: !status
      },(res) => {
        if(res && res.data && res.data.isSuccess) {
          wx.showModal({
            content: '确定执行该操作？',
            success (res) {
              if (res.confirm) {
                t.tabnavIndexChange({detail: {index: 2}})
              } else if (res.cancel) {
                api.setVisiTorsAnalyzeTop({
                  userId: target,
                  toppingStatue: status
                },() => {})
              }
            }
          })
        } else {
          wx.showToast({
            title: '操作失败,请稍后再试',
          })
        }
      })
    },

    onHideMe(e) {
      const {unionid,userId,target} = e.detail || {}
      wx.showModal({
          content: '屏蔽该访客后，将不再会看到该客户的访问记录以及客户分析数据',
        })
        .then((res) => {
          if (res.confirm) {
            api.setShiseldVisitor({
              userId,
              unionid,
            }, (res) => {
              if (res.data.isSuccess) {
                wx.showToast({
                  title: "屏蔽成功",
                  icon: "success",
                })
                if(target === 'TRACK') {
                  this.resetRecently()
                  this.queryVisitorList()
                }
                if(target === 'MANAGE') {
                  this.resetAnalyze()
                  this.getVisiTorsAnalyzeList(1)
                }
              } else {
                wx.showToast({
                  title: "屏蔽失败",
                  icon: "error",
                })
              }
            })
          }
        })
    }
  },

})